import SockJS from "sockjs-client"
import { Client, Stomp } from "@stomp/stompjs"
import { userStore } from "../../store/userStore";


export const connectionStompSockJS = () => {
    const token = userStore().userInfo.token;
    const uuId = userStore().userInfo.uu_id;

    const stompClient = new Client({
        webSocketFactory: () => {


            // 强制指定传输方式和协议
            const transportOptions = {
                transports: ['websocket', 'xhr-streaming'],     // 优先尝试WebSocket，失败后降级到xhr-streaming     传输方式的优先级
                server: "SockJS",
                debug: true
            }

            console.log('正在创建SockJS连接，使用传输方式:', transportOptions.transports);


            const sock = new SockJS("http://localhost:8080/snow-stomp", null, transportOptions)

            // 类型断言为any以访问内部属性
            const sockAny = sock as any;

            // 捕获SockJS底层传输的请求和响应
            sock.onopen = function () {
                console.log('SockJS连接已建立');
            };

            sock.onclose = function () {
                console.log('SockJS连接已关闭');
            };

            // 打印所有传输层消息
            sock.onmessage = function (e) {
                console.groupCollapsed('SockJS原始消息接收');
                console.log('消息数据:', e.data);
                console.groupEnd();
            };

            // 拦截XMLHttpRequest以获取请求头
            if (sockAny._transport && sockAny._transport.xhr) {
                const originalSend = sockAny._transport.xhr.send;
                sockAny._transport.xhr.send = function (data: any) {
                    console.groupCollapsed('SockJS请求详情');
                    console.log('请求方法:', this._method);
                    console.log('请求URL:', this._url);
                    console.log('请求头:', this._headers);
                    console.log('请求体:', data);
                    console.groupEnd();
                    return originalSend.apply(this, arguments);
                };

                const originalOpen = sockAny._transport.xhr.open;
                sockAny._transport.xhr.open = function (method: string, url: string) {
                    this._method = method;
                    this._url = url;
                    return originalOpen.apply(this, arguments);
                };

                sockAny._transport.xhr.onreadystatechange = function () {
                    if (this.readyState === 4) {
                        console.groupCollapsed('SockJS响应详情');
                        console.log('响应状态:', this.status);
                        console.log('响应头:', this.getAllResponseHeaders());
                        console.log('响应体:', this.responseText);
                        console.groupEnd();
                    }
                };
            }

            return sock;
        },
        connectHeaders: {
            Authorization: `Bearer ${token}`,
            'X-Requested-With': 'XMLHttpRequest' // 关键头
        },

        // 改进后的调试信息
        debug: (str) => {
            const frameMatch = str.match(/>>> (.*)/) || str.match(/<<< (.*)/);

            if (frameMatch) {
                const frame = frameMatch[1];
                console.groupCollapsed(`STOMP Frame: ${frame.substring(0, 50)}...`);
                console.log("Full Frame:", frame);

                try {
                    const stompCommand = frame.split('\n')[0];
                    console.log("STOMP Command:", stompCommand);

                    if (stompCommand.startsWith("MESSAGE")) {
                        const headers: Record<string, string> = {};
                        const lines = frame.split('\n');

                        for (let i = 1; i < lines.length; i++) {
                            const line = lines[i];
                            if (line === '') break;
                            const [key, value] = line.split(':');
                            if (key && value) headers[key.trim()] = value.trim();
                        }

                        console.log("Headers:", headers);

                        const bodyStart = frame.indexOf('\n\n');
                        if (bodyStart !== -1) {
                            const body = frame.substring(bodyStart + 2);
                            console.log("Body:", body);
                        }
                    }
                } catch (err) {
                    console.error("Failed to parse STOMP frame:", err);
                }

                console.groupEnd();
            } else {
                console.log("[STOMP Debug]:", str);
            }
        },

        heartbeatIncoming: 10000,
        heartbeatOutgoing: 10000,
        reconnectDelay: 5000,

        onConnect: (frame) => {
            console.log("Connected! Frame:", frame);

            stompClient.subscribe("/topic/public", (message) => {
                console.log("Public Message:", message.body);
            });

            stompClient.subscribe(`/user/queue/messages`, (message) => {
                console.log("Private Message:", message.body);
            });

            stompClient.publish({
                destination: "/app/chat",
                body: JSON.stringify({ content: "Hello, STOMP!" })
            });
        },

        onStompError: (frame) => {
            console.error("STOMP Error:", frame.headers?.message || frame.body);
        },

        onDisconnect: () => {
            console.log("Disconnected");
        }
    });

    stompClient.activate();
    return stompClient;
};